package com.face.pass.active.utils;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;


/**
 * 加密解密工具类
 */
public class AESUtil {

	private final static String HEX = "0123456789ABCDEF";
	private static final String transformation = "AES/CBC/PKCS5Padding";

	// 加密
	public static String encrypt(String key,String sSrc) throws Exception {
		Cipher cipher = Cipher.getInstance(transformation);
		byte[] raw = key.getBytes();
		SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
		IvParameterSpec iv = new IvParameterSpec(HEX.getBytes());// 使用CBC模式，需要一个向量iv，可增加加密算法的强度
		cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
		byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));
		return toHex(encrypted);// 此处使用BASE64做转码。
	}

	// 解密
	public static String decrypt(String key,String sSrc) throws Exception {
		try {
			byte[] raw = key.getBytes("utf-8");
			SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
			Cipher cipher = Cipher.getInstance(transformation);
			IvParameterSpec iv = new IvParameterSpec(HEX.getBytes());
			cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
			byte[] encrypted = toByte(sSrc);// 先用base64解密
			byte[] original = cipher.doFinal(encrypted);
			return new String(original, "utf-8");
		} catch (Exception ex) {
			return null;
		}
	}
	
	
	public static byte[] toByte(String hexString) {
        int len = hexString.length() / 2;
        byte[] result = new byte[len];
        for (int i = 0; i < len; i++)
            result[i] = Integer.valueOf(hexString.substring(2 * i, 2 * i + 2),
                    16).byteValue();
        return result;
    }

    public static String toHex(byte[] buf) {
        if (buf == null)
            return "";
        StringBuffer result = new StringBuffer(2 * buf.length);
        for (int i = 0; i < buf.length; i++) {
            appendHex(result, buf[i]);
        }
        return result.toString();
    }

    private static void appendHex(StringBuffer sb, byte b) {
        sb.append(HEX.charAt((b >> 4) & 0x0f)).append(HEX.charAt(b & 0x0f));
    }

}
